package org.k.reloadable.core.client;

import org.k.reloadable.core.ReloadObserver;
import org.k.reloadable.core.bean.Event;
import org.k.reloadable.core.bean.PropertyModifiedEvent;
import org.k.reloadable.core.cache.ICache;

/**
 * Created by hengxianwang on 16-12-20.
 */
public class ConfClient implements ReloadObserver{
    private ICache cache;

    public Object get(String key){
        Object obj = cache.get(key);
        if(obj == null){
            try {
                obj = ZkClient.getNodeData(key);
            } catch (Exception e) {
            }
        }
        return obj;
    }

    public void set(String key,Object value){
        this.cache.set(key, value);
    }

    public void del(String key){
        this.cache.del(key);
    }


    public ICache getCache() {
        return cache;
    }

    public void setCache(ICache cache) {
        this.cache = cache;
    }

    @Override
    public void update(PropertyModifiedEvent propertyModifiedEvent) {
        if(propertyModifiedEvent.getEvent().equals(Event.CREATE) || propertyModifiedEvent.getEvent().equals(Event.UPDATE)){
            this.set(propertyModifiedEvent.getPropertyName(), propertyModifiedEvent.getValue());
        }else if(propertyModifiedEvent.getEvent().equals(Event.DELETE)){
            this.del(propertyModifiedEvent.getPropertyName());
        }
    }
}
